import {Component, OnInit} from '@angular/core';
import {HttpService} from "../../../lib/service/http.service";
import {adSystemApiUrl, tuikeSystemUrl} from "../../../../config/api";
import {Headers, RequestOptions} from "@angular/http";
import {Router} from "@angular/router";


export class AddInvitation {
  number: string
}

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss']
})
export class InAddComponent implements OnInit {

  addInvitation = new AddInvitation;

  number = 0;
  type: string;
  message: string;
  isShow = false;
  addStatus = false;
  error = true;
  taskLoading = false;

  constructor(
    private httpService: HttpService,
    private router: Router
  ) {

  }

  ngOnInit() {

  }

  checkStatus(e) {
    if(e === null) {
      this.error = true;
    }else if (!/^([1-9]\d|\d)$/.test(e) || e == '0') {
      this.error = false;
    } else {
      this.error = true;
    }
  }

  add() {
      let url = `${tuikeSystemUrl}/api/v1/admin/invite_code/create`;
    if(this.error) {
      this.addStatus = true;
      const headers = new Headers({'Content-Type': 'application/json'});
      const options = new RequestOptions({headers: headers});
      const body = JSON.stringify({'count': this.addInvitation.number});
        return this.httpService.httpPostAuth(url, body, options).subscribe(
          res => {
            console.log(res);
            if (res.code == 200) {
              this.type = 'success';
              this.message = '添加成功';
              this.isShow = true;
              this.addStatus = false;
              this.router.navigate(['tuike/invitation/list']);
            } else {
              this.type = 'error';
              this.message = res.message;
              this.isShow = true;
              this.addStatus = false;
            }
          }
        );
    }
  }
}
